<?php
namespace Moyu\CloudEncrypt;

use GuzzleHttp\Client;

class Encrypt{

    protected $_parameter;
    protected $_base_api = 'https://encode.phpth.cn';
    protected $_encrypt_type = 'none';
    protected $_down_id;
    protected $_client;
    protected $_message;
    protected $_down_result;

    public function __construct($config = [])
    {
        $this->parameter();
        $this->setParameter($config);
        $this->_client = new Client([
            'base_uri' => $this->_base_api,
            'timeout'  => 5.0,
        ]);
    }

    /**
     * 提交参数
     */
    protected function parameter($array = []){
        $parameters = array_merge($array,['user','pass','apikey','file']);
        foreach($parameters as $parameter){
            $this->_parameter[$parameter] = '';
        }
    }

    /**
     * 加密
     */
    public function encrypt(){
        $this->_down_id = '';
        $response = $this->request();
        $this->_down_id = $response->down;
        $this->_message = $response->msg;
        return $this;
    }

    /**
     * 保存文件
     */
    public function saveFile($filePath){
        $this->_down_result = false;
        if(empty(trim($this->_down_id))){
            throw new CloudEncryptException(CloudEncryptException::ERROR_ENCRYPT_DOWN,CloudEncryptException::ERROR_ENCRYPT_DOWN_CODE);
        }
        if (!is_dir(dirname($filePath))) {
            mkdir(dirname($filePath), 0755, true);
        }
        $response = $this->_client->request('GET','/api.php?type=phpjm_down&mode='.$this->_encrypt_type.'&id='.$this->_down_id);
        $this->_down_result = file_put_contents($filePath,$response->getBody());
        return $this;
    }

    /**
     * 加密下载结果
     */
    public function success(){
        return $this->_down_result;
    }

    /**
     * 加密云端返回信息
     */
    public function message(){
        return $this->_message;
    }

    /**
     * 设置参数列表
     */
    public function setParameter($key, $value=null){
        if(is_array($key)){
            foreach($key as $keys => $value){
                if(array_key_exists($keys,$this->_parameter)){
                    $this->setParameter($keys,$value);
                }
            }
            return $this;
        }
        if($key != 'file'){
            $this->_parameter[$key] = $value;
        }
        return $this;
    }

    /**
     * 检查参数
     */
    protected function _checkParameter(){
        foreach($this->_parameter as $key => &$value){
            if($key == 'file'){
                continue;
            }
            $value = addslashes(trim($value));
            if(empty($value)){
                throw new CloudEncryptException(sprintf(CloudEncryptException::ERROR_PARAMETER,$key),CloudEncryptException::ERROR_PARAMETER_CODE);
            }
        }
    }

    /**
     * 设置上传文件
     */
    public function setFile($file){
        $file = str_replace(['/','\\'],DIRECTORY_SEPARATOR,$file);
        if(!is_file($file)){
            throw new CloudEncryptException(sprintf(CloudEncryptException::ERROR_FILE,$file),CloudEncryptException::ERROR_FILE_CODE);
        }
        $this->_parameter['file'] = fopen($file,'r');
        return $this;
    }

    /**
     * 发布云端加密任务
     */
    protected function request(){
        $this->_checkParameter();
        $body = [];
        $int = 0;
        foreach($this->_parameter as $key => $value){
            $body[$int]['name'] = $key;
            $body[$int]['contents'] = $value;
            $int++;
        }
        $response = $this->_client->request('POST','/api.php?type='.$this->_encrypt_type,['multipart' => $body]);
        $result = json_decode($response->getBody());
        if($result->code != 1){
            throw new CloudEncryptException($result->msg,$result->code);
        }
        return $result;
    }



}